package com.jmemoir.authorize.oauth2.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jmemoir.authorize.oauth2.entity.SysUser;
import com.jmemoir.authorize.oauth2.service.SysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 用户信息持久化
 *
 * @author Tellsea
 * @date 2023/8/18
 */
@Service
@RequiredArgsConstructor
public class SysUserDetailsServiceImpl implements UserDetailsService {

    private final SysUserService sysUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserService.getOne(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUserName, username));
        if (Objects.isNull(sysUser)) {
            throw new UsernameNotFoundException("用户不存在，或密码错误！");
        }
        return User.withUsername(sysUser.getUserName()).password(sysUser.getPassword()).roles("user").build();
    }
}
